import os
import random

import requests
import uuid
import datetime
import json


from app.project.doc_to_recommendation.llm.model.base_model import BaseModel
from app.project.doc_to_recommendation.utils.log_utils import log_func_call


class HttpChatBaseModel(BaseModel):
    def __init__(self, config: dict):
        super().__init__(config)
        print("=================config===============", config)
        self.model = config.get('model', 'qwen2-72b-int4')
        self.vl_model = config.get('vl_model', 'Qwen2.5-VL-7B-Instruct')
        self.api_url = config.get('api_url', 'http://localhost:8000/api/portal/v1/chat/completions')
        self.bind_t = config.get('bind_tools', False)
        # http请求组装共用报文
        self.llm_header_add_prps = {}
        self.fill_header_prps()
        # temperature = config.get('temperature', 0.3)
        self.tools = []
        if self.bind_t:
            self.bind_tools_df()

    def fill_header_prps(self):
        additional_prps = self.config.get('header_prps')
        if additional_prps is not None:
            self.llm_header_add_prps.update(additional_prps)


    def bind_tools_df(self):
        pass

    def bind_tools(self, tools):
        self.tools = tools
        self.model = self.model.bind_tools(tools)

    def agent_calls(self, text, image, prompt=None):
        # 构造输入信息
        human_mes_content = []
        self.model = self.model
        if image:
            human_mes_content.append({"type": "image_url", "image_url": {"url": "data:image/jpg;base64,%s" % (image)}})
            self.model = self.vl_model
        else:
            human_mes_content = [
                {"type": "text", "text": text}
            ]
        response = SendApiRequest(content=human_mes_content, system_prompt=prompt, model=self.model, api_url=self.api_url, add_header_prps=self.llm_header_add_prps)
        # 外呼llm
        return response


def SendApiRequest(
        content: list = [],
        system_prompt: str = "",
        model: str = "qwen2-72b-int4",
        api_url: str = "http://localhost:8000/api/portal/v1/chat/completions",
        timeout: int = 300000,
        add_header_prps: dict = None
    ):
    """
    发送自定义API请求

    参数:
    user_message: 用户消息内容 (默认: "你是谁")
    system_prompt: 系统提示词 (默认: "你是一个文档智能助手")
    model: 使用的模型名称 (默认: "qwen2-72b-int4")
    api_url: API端点URL
    custom_headers: 自定义请求头 (默认: {"Content-Type": "application/json"})
    timeout: 请求超时时间(秒)
    """
    # 生成唯一ID和跟踪号
    current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

    start_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:17]

    global_track_no = f"{current_time}997140214300752110"

    chat_id = '99714020000' + '0035' + start_time + str(random.randint(100, 999))

    # 默认请求头
    headers = {"Content-Type": "application/json"}
    # 附加请求头字段不为空，则将字段注入进header中
    headers.update(add_header_prps) if add_header_prps is not None else None
    # 可完全自定义的请求体
    payload = {
        "txHeader": {
            "servNo": "rag_v1_C011001",
            "startSysOrCmptNo": "99714020000",
            "sendSysOrCmptNo": "99714020000",
            "startChnlFgCd": "01",
            "busiSendInstNo": "11005293",
            "dataCenterCode": "Y",
            "txStartTime": start_time,
            "txSendTime": start_time,
            "msgrptTotalLen": "999",
            "msgrptFmtVerNo": "00001",
            "msgAgrType": "T",
            "pubMsgHeadLen": "999",
            "embedMsgrptLen": "999",
            "targetSysOrCmptNo": "99900180002",
            "servTpCd": "1",
            "servVerNo": "00001",
            "globalBusiTrackNo": global_track_no,
            "subtxNo": global_track_no,
            "reqSysSriNo": global_track_no,
            "resvedInputInfo": "0355"
        },
        "txBody": {
            "txEntity": {
                "chatId": chat_id,
                "stream": "true",
                "messages": [
                    {
                        "role": "user",
                        "content": content
                    }
                ],
                "variables": {
                    "prompt": system_prompt  # 可自定义的系统提示词
                },
                "sendSysOrCmptNo": "99714020000",
                "modelName": model,
                "bmdlJoinupSceneNo": "997140200000355"
            }
        }
    }

    try:
        with requests.post(
            api_url,
            headers=headers,
            json=payload,
            timeout=timeout,
            stream=True
        ) as response:
            response.raise_for_status()

            # 用于存储完整的响应
            full_response = {}
            full_content = ""

            # 处理所有块
            for chunk in response.iter_lines():
                content = process_chunk(chunk)
                if content:
                    # print(f"收到内容: '{content}'")
                    full_content += content

            print(f"full_content: '{full_content}'")

            return full_content

    except requests.exceptions.RequestException as e:
        error_info = {
            "error": str(e),
            "status_code": e.response.status_code if e.response else None,
            "response_text": e.response.text[:1000] if e.response else None
        }
        return error_info

def process_chunk(response_chunk):
    """处理单个响应块"""
    try:
        line_str = response_chunk.decode('utf-8')
        if line_str.startswith('data: '):
            line_str = response_chunk[6:]
        # 解析外层JSON
        data = json.loads(line_str)

        # 提取并解析内层JSON (txEntity.data)
        tx_entity_data = json.loads(data["txBody"]["txEntity"]["data"])

        # 检查是否有choices数组
        if "choices" in tx_entity_data and len(tx_entity_data["choices"]) > 0:
            choice = tx_entity_data["choices"][0]

            # 提取内容
            if "delta" in choice and "content" in choice["delta"]:
                content = choice["delta"]["content"]
                return content

    except (json.JSONDecodeError, KeyError) as e:
        pass

# ============= 使用示例 =============

if __name__ == '__main__':
    http = HttpChatBaseModel(config={'model':'qwen2-72b-int4', 'api_url':'http://20.208.42.182:80/online-service/rag/v1/C011002'})
    res2 = http.agent_calls("一句话介绍量子计算机",None, "你是计算机专家")
    print("默认请求响应res2:", res2)
    content = res2.get('txBody', {}).get('txEntity', {}).get('choices', [{}])[0].get('message', {}).get(
        'content', '')
    print("响应content:", content)